
import java.awt.print.PrinterException;
import java.sql.*;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javax.sound.midi.SysexMessage;
import javax.swing.JEditorPane;
import javax.swing.JTextArea;

/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
/**
 *
 * @author enrico
 */
public class PrestitiController {

  PrestitiView pv = new PrestitiView(this);
  private ObservableList<PrestitiModel> data;
  private Biblioteca controller;

  public PrestitiController(Biblioteca c) {
    // Popolo DB
    controller = c;
    
    /*data = FXCollections.observableArrayList();
      data.add(new PrestitiModel("Nome","Tizioni","La divina commedia","12-05-2012","12"));
      pv.getTV().setItems(data);*/
    try {

      data = FXCollections.observableArrayList();
      Class.forName("org.sqlite.JDBC");
      Connection conn = DriverManager.getConnection("jdbc:sqlite:lib/biblioteche.db");
      Statement stat = conn.createStatement();
      ResultSet rs = stat.executeQuery("SELECT nome,cognome,data,titolo,id_libro,durata FROM prestiti JOIN anagrafica ON anagrafica.ID = prestiti.ID_persona JOIN biblioteche ON biblioteche.ID = prestiti.ID_libro WHERE rientrato=0 ORDER BY data ASC");

      while (rs.next()) {
        data.add(new PrestitiModel(rs.getString("nome"), rs.getString("cognome"), rs.getString("titolo"), rs.getString("data"), rs.getString("id_libro"),rs.getString("durata")));
      }
      pv.getTV().setItems(data);
      rs.close();
      stat.close();
      conn.close();
    } catch (Exception exc) {
      System.out.println(exc.getMessage());
    }
  }

  public PrestitiView getView() {
    return pv;
  }

  void togliPrestito(PrestitiModel pm) {
    try {
      Class.forName("org.sqlite.JDBC");
      Connection conn = DriverManager.getConnection("jdbc:sqlite:lib/biblioteche.db");
      Statement stat = conn.createStatement();

      Calendar now = Calendar.getInstance();

      String oggi = now.get(Calendar.YEAR) + "-" + now.get(Calendar.MONTH) + 1 + "-" + now.get(Calendar.DAY_OF_MONTH);

      stat.executeUpdate("UPDATE prestiti SET rientrato=1, dataRientro=\"" + oggi + "\" WHERE rientrato=0 AND ID_libro=" + pm.getID());

      stat.close();
      conn.close();
      // aggiorno model
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }

  void setNuovoPrestito(int codiceLibro, int codicePersona, String data, int durata) {
    try {
      Class.forName("org.sqlite.JDBC");
      Connection conn = DriverManager.getConnection("jdbc:sqlite:lib/biblioteche.db");
      Statement stat = conn.createStatement();
      ResultSet rs = stat.executeQuery("SELECT nome,cognome,(SELECT titolo FROM biblioteche WHERE ID="+codiceLibro+") as titolo FROM anagrafica WHERE anagrafica.ID="+codicePersona);

      while (rs.next()) {
        PrestitiModel nuovo = new PrestitiModel(rs.getString("nome"), rs.getString("cognome"), rs.getString("titolo"), data, String.valueOf(codiceLibro), String.valueOf(durata));
        this.data.add(0, nuovo);
      }
      
      rs.close();
      stat.close();
      conn.close();
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }

  void stampaPrestito() {
    PrestitiModel pmTemp;
    pmTemp = pv.getSelectedModelPrestito();
    
    GregorianCalendar gc = new GregorianCalendar();
    int gg = gc.get(Calendar.DAY_OF_MONTH);
    int mese = gc.get(Calendar.MONTH) + 1;
    int anno = gc.get(Calendar.YEAR);
    
    JEditorPane jta = new JEditorPane("text/html", "");
    jta.setText("<div style=\"font-family:Arial\"><div style=\"margin-top: 100px\"><strong>PRESTITO LIBRO - "+gg+"/"+mese+"/"+anno+"</strong><br/><br/>"
            + "Titolo libro: "+pmTemp.getTitolo()+" (codice libro: "+pmTemp.getID()+")<br/>"+
      "Data prestito: "+pmTemp.getData()+"<br/>" +
      "Data restituzione: "+pmTemp.getRitorno()+"<br/>" +
      "Prestato a: "+pmTemp.getPersona()+"</div>");
    
    /*JTextArea jta = new JTextArea(
      "\n\n\n\n\n\n\n\nTitolo libro: "+pmTemp.getTitolo()+" (codice libro: "+pmTemp.getID()+")\n"+
      "Data prestito: "+pmTemp.getData()+"\n" +
      "Prestato a: "+pmTemp.getPersona()+"\n");*/
    
    //MessageFormat head = new MessageFormat("PRESTITO LIBRO - "+gg+"/"+mese+"/"+anno);
    MessageFormat head = new MessageFormat("");
    MessageFormat foot = new MessageFormat("");
    
    try {
      boolean complete = jta.print(head,foot);
      /*boolean complete = jta.print(MessageFormat.format("{data oggi} - PRESTITO LIBRO"),
                                         null, 
                                         true,
                                         null,
                                         null,
                                         interactive);*/
    } catch (PrinterException ex) {
      Logger.getLogger(PrestitiController.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
}
